package ServletController;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.dao.*;
import model.dto.*;
import builder.documentBuilder;

public class Servlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	public Servlet() {
		super();
	}

	public void init(ServletConfig config) throws ServletException {
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		try {
			process(request, response);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
	}

	protected void process(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException,SQLException {
		
		request.setCharacterEncoding("utf-8");	
		response.setContentType("text/html");
		
		HttpSession session = request.getSession();
		String userId = (String)session.getAttribute("user");
		String password = (String)session.getAttribute("password");
		
		System.out.println("======="+userId);  //user 아이디 검색해서 기존에 아이디가 있다면  크리에이트 테이블    
		System.out.println(loginDAO.selectAllUserId().contains(userId)); //없다면 그냥 건너 뛴다!
		
		//최초 처음 로그인(회원가입) 할때의 경우
 		if(loginDAO.selectAllUserId().contains(userId) == false){
 			accDAO.createTable(userId);  //회원DB에 userId 없으면 새로운 accclick_userId tables 만든다
 			loginDAO.insertUserId(new loginDTO(userId, password));  //회원DB에 등록한다
 		}
		
		String tagId = request.getParameter("service");
		String tagDate = request.getParameter("date");
		long tagIntDate = Long.parseLong(tagDate);

		accDTO dto1 = new accDTO(userId, tagId, tagIntDate, 1000, 0);
		accDTO dto2 = new accDTO(userId, tagId, tagIntDate, 1, 0);

		List li = accDAO.selectTagId(userId);

		if(li.size() != 0){
			for(int i=0;i<li.size(); i++){
				if (li.contains(tagId)) {
					accDAO.updateAccClick(dto1);
					break;
				} 
				else {
					accDAO.insertAccClick(dto2);
					break;
				}
			}
		}else{
			accDAO.insertAccClick(dto2);
		}

		documentBuilder.XMLBuilder(userId);
		System.out.println("XMLBuilder함수 실행완료");
	}
}